package com.learn.thread;

import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.concurrent.ThreadFactory;

public class MyThreadFactory implements ThreadFactory {

    private int counter;
    private String name;
    private List<String> statList;

    public MyThreadFactory(String name) {
        this.counter = 0;
        this.name = name;
        this.statList = new ArrayList<String>();
    }

    public String getStats() {
        StringBuffer buffer = new StringBuffer();
        Iterator<String> iterator = statList.iterator();
        // while (iterator.hasNext()) {
        //     buffer.append(iterator.next());
        //     buffer.append("\n");
        // }

        do {
            if (!iterator.hasNext()) {
                break;
            }
            buffer.append(iterator.next());
            buffer.append("\n");
        } while (true);

        return buffer.toString();
    }

    @Override
    public Thread newThread(Runnable r) {
        Thread thread = new Thread(r, name + "-Thread_" + counter);
        counter++;
        statList.add(String.format("Created thread %d with name %s on %s\n", thread.getId(), thread.getName(), new Date()));
        return thread;
    }

}
